/**
 * Schedule Proxy
 */
var models = require('../models');
var Schedule = models.Schedule;
var User = require('./user');
var Reply = require('./reply');
var tools = require('../common/tools');
var at = require('../common/at');
var _ = require('lodash');
var Q = require('q');
var logger = require('../common/loggerUtil').getLogger('schedule');


function _friendlyDate(doc) {
    if (doc.create_date) {
        doc.friendly_create_at = doc.create_date.toFormat("YYYY-MM-DD HH24:MI:SS");
    }

    if (doc.update_date) {
        doc.friendly_update_at = doc.update_date.toFormat("YYYY-MM-DD HH24:MI:SS");
    }

    return doc;
}


exports.newAndSave = function(category, name, time_settings, author_id, assignee,
    description) {
    var deferred = Q.defer();
    var s = new Schedule();
    s.category = category;
    s.name = name;
    s.time_settings = time_settings;
    s.author = author_id;
    s.assignee = assignee;
    s.description = description;
    s.save(function(err, doc) {
        if (err) {
            deferred.reject(err);
        } else {
            deferred.resolve(doc);
        }
    });
    return deferred.promise;
}

function _getScheduleById(_id) {
    var deferred = Q.defer();
    Schedule.findById(_id)
        .populate('author')
        .exec(function(err, result) {
            if (err) {
                deferred.reject({
                    message: '此记录不存在或已被删除。',
                    reason: err,
                    code: 1
                });
            } else {
                deferred.resolve(result);
            }
        });
    return deferred.promise;
}

function _getSchedulesByQuery(query, options) {
    var METHOD = 'getSchedulesByQuery';
    var deferred = Q.defer();
    Schedule.find(query, '_id name create_date update_date author schedule_id', options)
        .populate('author')
        .exec(function(err, result) {
            if (err) {
                deferred.reject(err);
            } else if (result.length == 0) {
                deferred.resolve([]);
            } else {
                // var topics_id = _.pluck(result, 'id');
                // logger.debug(METHOD, 'Get ' + JSON.stringify(topics_id));
                deferred.resolve(_.map(result, _friendlyDate));
            }
        });

    return deferred.promise;
}

exports.getCountByQuery = function(query, callback) {
    Schedule.count(query, callback);
}

exports.findAllSchedule = function() {
    var deferred = Q.defer();
    Schedule.find({}, function(err, docs) {
        if (err) {
            deferred.reject(err);
        } else {
            deferred.resolve(docs);
        }
    });
    return deferred.promise;
}


exports.getSchedulesByQuery = _getSchedulesByQuery;
exports.getScheduleById = _getScheduleById;
